package com.lrz.controller;


import com.lrz.common.Result;
import com.lrz.util.MinIOUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    @Resource
    private MinIOUtil minIOUtil;

    @RequestMapping("/toIndex")
    public String toIndex(){
        return "test1";
    }

    @RequestMapping("/toIndex1")
    public String toIndex1(){
        return "test2";
    }

    /***
     * md图片上传
     * @return
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public Map upload(@RequestParam("editormd-image-file") MultipartFile file) throws Exception {
//        System.out.println("哈哈哈哈哈哈");
//        JSONObject jsonObject = new JSONObject();
        Map<String, Object> jsonObject = new HashMap<>();
        Result upload = minIOUtil.upload(file);
        Map<String, String> data = (Map<String, String>) upload.getData();
        if (data != null){
            jsonObject.put("success", 1);
            jsonObject.put("message", "上传成功");
            jsonObject.put("url", data.get("url"));
        }else{
            jsonObject.put("success", 0);
            jsonObject.put("message", "上传失败");
        }
        System.out.println(jsonObject);
        return jsonObject;
    }

    @PostMapping("/uploadFile")
    @ResponseBody
    public Result updateFile(@RequestParam("file") MultipartFile multipartFile){
        return minIOUtil.upload(multipartFile);
    }

    /***
     * 文件上传
     * @return
     */
    @PostMapping(value = "/file/upload")
    @ResponseBody
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
//        System.out.println("哈哈哈哈哈哈");
//        JSONObject jsonObject = new JSONObject();
//        Map<String, Object> jsonObject = new HashMap<>();
        Result upload = minIOUtil.upload(file);
//        Map<String, String> data = (Map<String, String>) upload.getData();
        return upload;
    }

    @RequestMapping("/download/{fileName}")
    public void download(HttpServletResponse response, @PathVariable("fileName") String fileName){
        minIOUtil.download(response, fileName);
//        return new Result(true, StatusCode.OK, "下载成功");
    }
}
